import {DataTable, Searchbar} from 'react-native-paper';
import React, {useEffect, useState, useRef, useCallback} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  StyleSheet,
  Pressable,
} from 'react-native';
import {ActivityIndicator} from 'react-native-paper';
import LinearGradient from 'react-native-linear-gradient';
import {getFindPatrolPolice} from 'api/police';
import BaseCol from 'components/BaseCol';
import useDimensions from 'hooks/useDimensions';
import {useFocusEffect} from '@react-navigation/native';
type ListItem = Api.resBody['警情信息主表'];
export default ({navigation}: RootStackScreenProps) => {
  const Scale = useDimensions();
  const [loading, setLoading] = useState(true);
  const styles = StyleSheet.create({
    type: {
      fontSize: 22 * Scale,
      fontWeight: '500',
    },
    inactive: {
      fontSize: 26 * Scale,
      color: ' rgba(0,0,0,0.9)',
      lineHeight: 30 * Scale,
    },
    textBg: {
      width: 114 * Scale,
      height: 16 * Scale,
      borderRadius: 10,
      // backgroundColor: 'rgba(10, 89, 247, 0.80)',
      position: 'absolute',
      top: 18 * Scale,
    },
  });
  const [page, setPage] = React.useState<number>(0),
    [searchQuery, setSearchQuery] = React.useState('');
  const [numberOfItemsPerPageList] = React.useState([5, 10, 15]);
  const [itemsPerPage, onItemsPerPageChange] = React.useState(
    numberOfItemsPerPageList[1],
  );
  const PageDataList = useRef<ListItem[]>();

  const [items, setItems] = React.useState<ListItem[]>([]);
  const [inactive, setInactive] = useState(0);
  const from = page * itemsPerPage;
  const onChangeSearch = (query: string) => setSearchQuery(query);
  const to = Math.min((page + 1) * itemsPerPage, items.length);

  useFocusEffect(
    useCallback(() => {
      setLoading(true);
      getFindPatrolPolice()
        .then(data => {
          PageDataList.current = data?.slice() ?? [];
          setItems(PageDataList.current);
          setLoading(false);
        })
        .catch(() => {
          setLoading(false);
        });
    }, []),
  );
  useEffect(() => {
    setItems(
      (PageDataList.current ?? []).filter(item => {
        if (inactive === 1) {
          return (
            [1, 0].includes(item.executionStatus ?? 0) &&
            item.address?.includes(searchQuery)
          );
        } else {
          return item.address?.includes(searchQuery);
        }
      }),
    );
  }, [inactive, searchQuery]);
  // 判断警情---1-3级显示#0A59F7
  const isLowLevel = (data: ListItem['incidentLevel']) => {
    return ['一级', '二级', '三级'].includes(data ?? '');
  };
  return (
    <View
      style={{
        flex: 1,
        backgroundColor: '#fff',
      }}>
      <ActivityIndicator
        animating={loading}
        style={{
          position: 'absolute',
          left: '50%',
          top: '50%',
          zIndex: 100,
        }}
        size={'large'}
      />
      <DataTable
        style={{
          marginTop: 52 * Scale,
          flex: 1,
        }}>
        <DataTable.Header>
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              marginBottom: 10 * Scale,
              flex: 1,
            }}>
            <View style={{flexDirection: 'row'}}>
              <Pressable
                onPress={() => {
                  setInactive(0);
                }}>
                <Text
                  style={[
                    styles.type,
                    inactive === 0 ? styles.inactive : undefined,
                    {
                      marginRight: 32 * Scale,
                    },
                  ]}>
                  全部警情
                </Text>
                {inactive === 0 && (
                  <LinearGradient
                    colors={['rgba(10, 89, 247, 0)', 'rgba(10, 89, 247, 0.80)']}
                    useAngle
                    angle={270}
                    style={styles.textBg}
                  />
                )}
              </Pressable>
              <Pressable
                onPress={() => {
                  setInactive(1);
                }}>
                <Text
                  style={[
                    styles.type,

                    inactive === 1 ? styles.inactive : undefined,
                  ]}>
                  未完成警情
                </Text>
                {inactive === 1 && (
                  <LinearGradient
                    colors={['rgba(10, 89, 247, 0)', 'rgba(10, 89, 247, 0.80)']}
                    useAngle
                    angle={270}
                    style={styles.textBg}
                  />
                )}
              </Pressable>
            </View>
            <View>
              <Searchbar
                style={{
                  width: 400,
                  height: 48,
                  transform: [
                    {
                      scale: Scale,
                    },
                  ],
                }}
                inputStyle={{
                  minHeight: 50 * Scale,
                }}
                placeholder="输入警情地址"
                onChangeText={onChangeSearch}
                value={searchQuery}
              />
            </View>
          </View>
        </DataTable.Header>
        <ScrollView
          style={{
            flex: 1,
          }}>
          {items.slice(from, to).map((item, index) => (
            <DataTable.Row key={index}>
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  flex: 1,
                }}>
                <BaseCol
                  span={5}
                  style={{
                    paddingHorizontal: 10,
                  }}>
                  <Text>{item.address}</Text>
                </BaseCol>
                <BaseCol
                  span={4}
                  style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                  }}>
                  <Text>{item.incidentType}</Text>
                  <View
                    style={{
                      width: 72 * Scale,
                      height: 24 * Scale,
                      borderRadius: 2,
                      borderWidth: 1,
                      borderColor: isLowLevel(item.incidentLevel)
                        ? '#0A59F7'
                        : '#F53F3F',
                      marginLeft: 6 * Scale,
                    }}>
                    <Text
                      style={{
                        fontSize: 14 * Scale,
                        lineHeight: 22 * Scale,
                        textAlign: 'center',
                        color: isLowLevel(item.incidentLevel)
                          ? '#0A59F7'
                          : '#F53F3F',
                      }}>
                      {item.incidentLevel + '警情'}
                    </Text>
                  </View>
                </BaseCol>
                <BaseCol span={5}>
                  <Text> {item.incidentTime}</Text>
                </BaseCol>
                <BaseCol span={6}>
                  <Text> {item.incidentDes}</Text>
                </BaseCol>
                <BaseCol span={4} style={{flexDirection: 'row'}}>
                  <TouchableOpacity
                    onPress={() => {
                      navigation.navigate('PoliceInfo', {
                        id: item.id,
                      });
                    }}>
                    <Text
                      style={{
                        color: '#0A59F7',
                        paddingLeft: 15 * Scale,
                        paddingRight: 15 * Scale,
                      }}>
                      查看详情
                    </Text>
                  </TouchableOpacity>
                  <TouchableOpacity
                    onPress={() => {
                      const {
                        incidentLatitude: latitude,
                        incidentLongitude: longitude,
                        id,
                      } = item;
                      navigation.navigate('PoliceMap', {
                        position: {
                          latitude: Number(latitude) as unknown as number,
                          longitude: Number(longitude) as unknown as number,
                        },
                        patrolPoliceId: id + '',
                      });
                    }}>
                    <Text
                      style={{
                        color: '#0A59F7',
                        paddingLeft: 15 * Scale,
                        paddingRight: 15 * Scale,
                      }}>
                      作战部署
                    </Text>
                  </TouchableOpacity>

                  <Text style={{color: '#0A59F7'}} />
                </BaseCol>
              </View>
            </DataTable.Row>
          ))}
        </ScrollView>
        <DataTable.Pagination
          page={page}
          numberOfPages={Math.ceil(items.length / itemsPerPage)}
          onPageChange={page => setPage(page)}
          label={`${from + 1}-${to} of ${items.length}`}
          numberOfItemsPerPageList={numberOfItemsPerPageList}
          numberOfItemsPerPage={itemsPerPage}
          onItemsPerPageChange={onItemsPerPageChange}
          showFastPaginationControls
          style={{
            padding: 10,
          }}
        />
      </DataTable>
    </View>
  );
};
